/**
 * components util
 */

/**
 * 清理空值，对象
 * @param children
 * @returns {*[]}
 */
export function filterEmpty (children = []) {
  return children.filter(c => c.tag || (c.text && c.text.trim() !== ''))
}

/**
 * 获取字符串长度
 * @param {*} str
 * @param {*} type 1 - 英文字符长度1，中文字符长度2, 2 - 中文英文都是1
 */
export const getStrFullLength = (str = '', type = 2) => {
  str = str || ''
  return str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (type === 1) {
      if (charCode >= 0 && charCode <= 128) {
        return pre + 1
      }
      return pre + 2
    } else {
      return pre + 1
    }
  }, 0)
}

/**
 * 截取字符串，根据 maxLength 截取后返回
 * @param {*} str
 * @param {*} maxLength
 */
export const cutStrByFullLength = (str = '', maxLength, type = 2) => {
  let showLength = 0
  str = str || ''
  return str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (type === 1) {
      if (charCode >= 0 && charCode <= 128) {
        showLength += 1
      } else {
        showLength += 2
      }
    } else {
      showLength += 1
    }
    if (showLength <= maxLength) {
      return pre + cur
    }
    return pre
  }, '')
}
